package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.RoleMenuDao;
import com.aaa.vegetablemarketexpress.entity.RoleMenu;
import com.aaa.vegetablemarketexpress.service.RoleMenuService;
import com.aaa.vegetablemarketexpress.util.CustomException;
import com.aaa.vegetablemarketexpress.util.ResultStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @FileName: RoleMenuServiceImpl
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/9 15:30
 * @Version: 1.0.0
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Resource
    private RoleMenuDao roleMenuDao;

    /**
     * 角色分配菜单权限
     * @param roleId
     * @param menuIds
     */
    @Override
    public void assignMenusToRole(Long roleId, List<Long> menuIds) {
        if (roleId == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID不能为空");
        }
        // 先删除原有的菜单权限
        roleMenuDao.deleteByRoleId(roleId);

        if (menuIds != null && !menuIds.isEmpty()) {
            // 批量插入新的菜单权限
            List<RoleMenu> roleMenuList = new ArrayList<>();
            for (Long menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu(roleId, menuId);
                roleMenuList.add(roleMenu);
            }
            roleMenuDao.batchInsert(roleMenuList);
        }
    }

    /**
     * 获取角色拥有的菜单ID列表
     * @param roleId
     * @return
     */
    @Override
    public List<Long> getMenuIdsByRoleId(Long roleId) {
        if (roleId == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID不能为空");
        }
        return roleMenuDao.selectMenuIdsByRoleId(roleId);
    }

    /**
     * 删除角色的所有菜单权限
     * @param roleId
     */
    @Override
    public void removeAllMenusFromRole(Long roleId) {
        if (roleId == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID不能为空");
        }
        roleMenuDao.deleteByRoleId(roleId);
    }

    /**
     * 检查角色是否有某个菜单权限
     * @param roleId
     * @param menuId
     * @return
     */
    @Override
    public boolean hasMenuPermission(Long roleId,Long menuId) {
        if (roleId == null || menuId == null) {
            return false;
        }
        return roleMenuDao.checkRoleMenuExists(roleId, menuId) > 0;
    }
}

